#import scanf
import parse
import fire
import time
import datetime
import os
import random
from math import sin

# 输出log，便于调试
import logging


def update_data_dict_gen(t=None,mode='sin',selected_cols=None,data_types=None):
    """假造一些数据，返回字典格式
    """
    now_ts = time.time() if t is None else t # 默认当前时间
    update_data_dict = {}
    
    # 时间处理
    update_data_dict['DateTime'] = now_ts

    # 生成数据
    if mode == 'sin':
        # 正弦变化的数据
        period = 100 # s
        shift = 10 # s
        for i,col in enumerate(selected_cols):
            if data_types[col] == 'f':
                update_data_dict[col] = 1000*(2+sin((now_ts+shift*i)/period))
            elif data_types[col] == 'd':
                update_data_dict[col] = int(1000*(1+sin((now_ts+shift*i)/period)))
            else :
                raise RuntimeError(f'unknown data type {col}:{data_types[col]}')
    elif mode == 'random':
        # 随机数据
        max = 1.0
        min = 0.0
        for i,col in enumerate(selected_cols):
            update_data_dict[col] = random.random()*(max-min)+min
    else:
        raise RuntimeError(f'mode={mode}, it must be "sin" or "random"')
    return update_data_dict

def main(output_filename= None,
        delay_time = 0.95,
        test_mode=False,
        max_time_hours = 24,
        mode='sin',
        log_level = 'INFO'):
    """假造一些输出到log文件，模拟实际设备
    """
    # 初始化
    logging.basicConfig(level = getattr(logging,log_level.upper(),logging.INFO)) # 默认info
    file_base_name = os.path.basename(__file__)
    logger = logging.getLogger(file_base_name)

    # 分隔符
    sep = ','
    # 列名
    col_names = 'DateTime,TimeSSM,Status,DataStatus,PartCt,HistSum,PartCon,BL,BLTH,STD,MaxSTD,P,TofP, PumpLife_hrs,WidthSTD,AveWidth, POPS_Flow, PumpFB, LDTemp, LaserFB, LD_Mon, Temp, BatV, Laser_Current, Flow_Set,BL_Start,TH_Mult,nbins,logmin,logmax,Skip_Save,MinPeakPts,MaxPeakPts,RawPts,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15'.split(sep)
    col_names = [n.strip() for n in col_names]
    # 格式
    # example 
    # 1610010201.664,32601.6641,3,2,6947,6947,5680.02,2125,2149,8.06,13.72,1033.35,25.74,105.64,0.00,0.00,1.22,69.45,36.50,621.54,757.80,26.15,11.24,2.87,1.90,30000,3.0,16,1.00,4.81,0,8,255,512,0,7,2385,3036,402,312,289,241,222,38,12,2,1,0,0,0
    write_formats = ['14.3f','.4f']+['d']*4+['.2f','d','d']+['.2f']*16+['d','f','d','.2f','.2f']+['d']*20
    read_formats = [format[-1] for format in write_formats]

    # data types
    data_types = dict(zip(col_names, read_formats))

    # selected cols
    selected_cols = [col.strip() for col in 'PartCon,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15'.split(',') ]
    
    # 默认值，为保持完整性
    defaults_str = '1610010201.664,32601.6641,3,2,6947,6947,5680.02,2125,2149,8.06,13.72,1033.35,25.74,105.64,0.00,0.00,1.22,69.45,36.50,621.54,757.80,26.15,11.24,2.87,1.90,30000,3.0,16,1.00,4.81,0,8,255,512,0,7,2385,3036,402,312,289,241,222,38,12,2,1,0,0,0'

    # 第一行
    header = sep.join(col_names)
    logger.info(header)

    # 生成格式化字符串
    line_write_formatter=sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names,write_formats)])
    logger.info(line_write_formatter)

    line_read_formatter=sep.join([f'{{{col_name}:{format}}}' for col_name,format in zip(col_names,read_formats)])
    logger.info(line_read_formatter)

    # 简单测试
    parse_result = parse.parse(line_read_formatter,defaults_str)
    logger.info(parse_result)
    if parse_result is None:
        raise RuntimeError('Something go wrong!')

    # 默认值
    data_dict_defaults = parse_result.named

    # example data
    # raw_data_example_filename = r"raw_data\课题3\POPS\POPS_20210107x003.csv"
    
    # 输出文件名
    output_filename = output_filename if output_filename is not None else (file_base_name+r".test.log")
    with open(output_filename,'w+',encoding='utf-8') as OF:
        if test_mode: OF = None
        #header
        print(header,file=OF)
        #lines
        start_time = time.time()
        while(time.time()<start_time + max_time_hours*24*3600): # max hours
            data_dict = data_dict_defaults
            update_data_dict = update_data_dict_gen(mode=mode,selected_cols=selected_cols,data_types=data_types)
            logger.info(update_data_dict)
            data_dict.update(update_data_dict)
            line = line_write_formatter.format(**data_dict)
            print(line,file=OF,flush=True)# flush is necessary
            time.sleep(delay_time)

if __name__ == "__main__":
    fire.Fire(main) # 利用fire命令行化